package com.offcn.member.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.offcn.common.utils.JWTUtil;
import com.offcn.common.utils.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.common.utils.PageUtils;
import com.offcn.common.utils.Query;

import com.offcn.member.dao.MemberDao;
import com.offcn.member.entity.MemberEntity;
import com.offcn.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("id",key).or().like("user_name",key);
        }
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<Map<String, Object>> countByDateTime(String beginTime, String endTime) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        //格式化时间查询  时间区间的总注册数
        wrapper.select("DISTINCT(DATE_FORMAT(create_time,'%y-%m-%d')) AS NAME,COUNT(id) AS VALUE")
                .between("create_time",beginTime+" 00:00:00",endTime+" 23:59:59")
                .groupBy("name");
        List<Map<String, Object>> mapList = baseMapper.selectMaps(wrapper);
        return mapList;
    }

    @Override
    public R login(String username, String password) {
        //查询用户
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>()
                .eq("user_name", username).eq("PASSWORD", password));
        //如果用户不为空
        if(null != memberEntity){
            //生成签名
            String token = JWTUtil.generateToken(memberEntity.getUserName());
            //生成refreshToken
            String refreshToken = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForHash().put(refreshToken,"token",token);
            stringRedisTemplate.opsForHash().put(refreshToken,"username",username);
            //设置token的过期时间
            stringRedisTemplate.expire(refreshToken,JWTUtil.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);
            return R.ok().put("token",token).put("refreshToken",refreshToken);
        }else {
            return R.error("账号密码错误");
        }
    }

}